<template>
  <el-dialog top="25vh" :model-value="props.visible" @close="onClose" :title="t('flypass.new_pass')" width="600px">
    <el-form label-position="top" ref="form" :model="formData" :rules="rules">
      <el-form-item :label="t('modules.pass.pass_name')" required prop="passName">
        <el-input v-model="formData.passName"></el-input>
      </el-form-item>

      <el-form-item :label="t('common.description')" prop="remark">
        <el-input type="textarea" v-model="formData.remark"></el-input>
      </el-form-item>
    </el-form>  
    <template #footer>
      <div class="text-right">
        <el-button @click="onClose">{{ t('common.cancel') }}</el-button>
        <el-button type="primary" @click="confirm" :loading="loading">{{ t('common.confirm') }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { newTopic } from '@/api/topic/topic';
import type { FormInstance, FormRules } from '@toms/element-ui'


interface PassFormData {
  passName: string
  remark: string
}

const { t } = useI18n()
const loading = ref(false)
const form = ref<FormInstance | null>(null)
const emits = defineEmits(['update:visible', 'save'])
const props = defineProps<{visible: boolean}>()
const formData = ref<PassFormData>({
  passName: '',
  remark: ''
})

const rules = reactive<FormRules<PassFormData>>({
  passName: [{
    required: true,
    message: t('flypass.pass_name_required')
  }]
})

function onClose() {
  formData.value.passName = ''
  formData.value.remark = ''
  form.value?.clearValidate()
  emits('update:visible', false)
}

function confirm() {
  if(form && form.value) {
    form.value.validate(async(valid) => {
      if (valid) {
        loading.value = true
        await newTopic({
          passName: formData.value.passName,
          remark: formData.value.remark
        })
        loading.value = false
        form.value?.clearValidate()
        emits('update:visible', false)
        emits('save')
      }
    })
  }
}
</script>
